package com.example.netactivity;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleAdapter;

import androidx.annotation.NonNull;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;

public class MyListActivity extends ListActivity implements AdapterView.OnItemClickListener,AdapterView.OnItemLongClickListener {
    private static final String TAG = "MyListActivity";

    private ArrayList<HashMap<String,String>> listItems;
    private SimpleAdapter listItemAdapter;
    private Handler handler;
    private MyAdapter adapter;
    private String logDate = "";
    private final String DATE_SP_KEY = "lastRateDateStr";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setContentView(R.layout.activity_rate_list);

        SharedPreferences sp = getSharedPreferences("myrate", Context.MODE_PRIVATE);
        logDate = sp.getString(DATE_SP_KEY, "");
        Log.i("List","lastRateDateStr=" + logDate);

        handler = new Handler(Looper.myLooper()){
            @Override
            public void handleMessage(@NonNull Message msg){
                if(msg.what==9){
                    Log.i(TAG, "handleMessage: "+msg.obj);
                    //listItems = (ArrayList<Item>)msg.obj;
                    Log.i(TAG,"handleMessage:list.size:"+listItems.size());
//                    listItemAdapter = new SimpleAdapter(MyListActivity.this,listItems,//listItems数据源
 //                           R.layout.list_item,//listItem的布局实现
//                            new String[]{"ItemTitle","Price"},
 //                           new int[]{R.id.itemTitle,R.id.price}
//                    );
                    ItemAdapter itemadapter = new ItemAdapter(MyListActivity.this,R.layout.list_item,(ArrayList<Item>)msg.obj);
                    setListAdapter(itemadapter);
                    //Log.i(TAG, "handlerMessage: setListAdapter");
                }
                super.handleMessage(msg);
            }
        };

        //准备数据项
        initListView();
        setListAdapter(listItemAdapter);
        getListView().setOnItemClickListener(this);
        getListView().setOnItemLongClickListener(this);

        //启动线程
        Thread t = new Thread(()->{
            //获取网络数据，带回list
            ArrayList<HashMap<String,String>> retlist = new ArrayList<HashMap<String,String>>();
            try {
                Log.i(TAG, "run:正在工作。。。");

                Document doc = Jsoup.connect("https://chl.cn/?jinri").get();
                Elements tables = doc.getElementsByTag("table");
                Element table1 = tables.first();
                //查找tr
                Elements rows = table1.getElementsByTag("tr");
                rows.remove(0);

                for (Element row : rows) {
                    //拆分单元格td
                    Elements tds = row.getElementsByTag("td");
                    Element td1 = tds.first();
                    Element td2 = tds.get(4);//第五列表格，即第一列是0开始
                    String str1 = td1.text().trim();
                    String str2 = td2.text().trim();

                    Log.i(TAG, "run:币种:" + td1.text() + "价格：" + td2.text());
                    Log.i(TAG, "run:币种2:" + td1.html() + "价格2:" + td2.html());

                    HashMap<String,String> map = new HashMap<String,String>();
                    map.put("ItemTitle",str1);   //标题文字
                    map.put("Price",str2);    //价格

                    retlist.add(map);
                    Log.i(TAG,td1.text() + "=>" + td2.text() );
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }

            //发送数据给主线程
            Message msg = handler.obtainMessage(9,retlist);
            handler.sendMessage(msg);
        });
       // t.start();
        Thread t2 = new Thread(new ItemTask(handler));
        t2.start();
    }

    private void initListView(){
        listItems = new ArrayList<HashMap<String,String>>();
        for(int i=0;i<10;i++){
            HashMap<String,String> map = new HashMap<String,String>();
            map.put("ItemTitle","Rate: "+i);   //标题文字
            map.put("Price","detail" +i);    //详情描述
            listItems.add(map);
        }
        //生成适配器的Item和动态数组对应的元素
        listItemAdapter = new SimpleAdapter(this,listItems,//listItems数据源
                R.layout.list_item,  //listItem的xml布局实现
                new String[]{"ItemTitle","Price"},
                new int[]{R.id.itemTitle,R.id.price}
        );
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        //获取当前选中行数据
        Log.i(TAG,"onItemClick:单机执行");
        HashMap<String,String> map = (HashMap<String,String>)getListView().getItemAtPosition(position);
        String titleStr = map.get("ItemTitle");
        String priceStr = map.get("Price");
        Log.i(TAG,"onItemClick:Title="+titleStr);
        Log.i(TAG,"onItemClick:Price="+priceStr);
        Log.i(TAG,"onItemClick:position"+position);
     //   Intent intent = new Intent(this,ListResult.class);  转换到显示汇率的界面并进行计算
     //   intent.putExtra("name",title);
     //   intent.putExtra("value",price);
     //   this.startActivity(intent);
        //删除当前数据项
       // adapter.remove(map);
        listItems.remove(position);
        listItemAdapter.notifyDataSetChanged();
        }
    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView,View view,int i,long l){
        Log.i(TAG,"onItemLongClick:长按执行");
        HashMap<String,String>map = (HashMap<String, String>)getListView().getItemAtPosition(i);
        //提示删除操作
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示").setMessage("请确认是否删除当前数据").setPositiveButton("是",new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog,int which){
                Log.i(TAG,"onClick:对话框事件处理");
                  listItems.remove(i);
                  listItemAdapter.notifyDataSetChanged();
          //      adapter.remove(map);
            }
        }).setNegativeButton("否",null);             //上方setPositive,当前setNegative   不能混乱顺序
        builder.create().show();
        Log.i(TAG,"onItemLongClick:size="+ listItems.size());
        return true;
    }
}


//长按return false  会激活单击事件,   return true 不激活